from django.contrib.auth import login
from django.shortcuts import render, redirect
from django.views import View
from QQLoginTool.QQtool import OAuthQQ
from django.conf import settings
from django import http
import re

from django_redis import get_redis_connection

from oauth.models import Oauthuser
from users.models import User
from .utils import Jia_mi,Jie_mi


class Oauthview(View):
    def get(self,request):
        #获取参数
        state = request.GET.get('next','/')
        #创建OAuthQQ对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI, state=next)
        #获取qq页面
        login_url = oauth.get_qq_url()
        #返回响应
        return http.JsonResponse({"login_url":login_url})

class Oauthuserview(View):
    def get(self,request):

        #获取参数
        code = request.GET.get('code')
        state = request.GET.get('state')

        if not code:
            return http.HttpResponseForbidden('没有获取code')

        #创建一个对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI, state=next)
        #获取token
        access_token = oauth.get_access_token(code)
        #获取openid
        openid = oauth.get_open_id(access_token)

        try:
            #获取用户对象
            oauth_user_qq = Oauthuser.objects.get(openid=openid)
        except Oauthuser.DoesNotExist:
            sign_openid = Jia_mi(openid)
            return render(request,'oauth_callback.html',context={'token':sign_openid})
        else:
            #根据openid获取对象
            oauth_user_qq = Oauthuser.objects.get(openid=openid)

            #通过qq用户对象得到用户
            user = oauth_user_qq.user
            #状态保持
            login(request,user)
            request.session.set_expiry(3600*24*2)#设置保持状态的时间
            #返回响应
            response = redirect('/')
            response.set_cookie('username',user.username)

            return response

    def post(self,request):
        #获取参数
        sign_openid = request.POST.get('access_token')
        mobile = request.POST.get('mobile')
        pwd = request.POST.get('pwd')
        sms_code = request.POST.get('sms_code')
        #校验参数
        if not all([sign_openid,mobile,pwd,sms_code]):
            return http.HttpResponseForbidden('参数不全')
        #校验openid
        openid = Jia_mi(sign_openid)
        if not openid:
            return http.HttpResponseForbidden('openid获取错误')
        #校验手机号
        if not re.match(r'^1[345789]\d{9}$',mobile):
            return http.HttpResponseForbidden('手机号格式有误')
        #校验密码
        if not re.match(r'[0-9A-Za-z]{8,20}$',pwd):
            return http.HttpResponseForbidden('密码有误')
        #获取验证码
        redis_conn = get_redis_connection('code')
        redis_sms_code = redis_conn.get('sms_code_%s'%mobile)

        #判断验证码是否过期
        if not redis_sms_code:
            return http.HttpResponseForbidden('验证码过期')
        #如果没过期，判断验证码在redis中是否一致
        if sms_code != redis_sms_code.decode():
            return http.HttpResponseForbidden('验证码填写错误')

        #查看是否存在用户，存在直接绑定，不存在创建后在绑定
        try:
            user = User.objects.get(mobile=mobile)
        except Exception:
            #不存在创建一个用户
            user = User.objects.create_user(username=mobile,password=pwd,mobile=mobile)
            # 绑定用户到数据库
            Oauthuser.objects.create(user=user, openid=openid)
            #状态保持
            login(request,user)
            request.session.set_expiry(3600*24*2)
            #返回响应
            #返回到首页
            response = redirect('/')
            #设置时间
            response.set_cookie('username',user.username,max_age=3600*24*2)
            #返回响应
            return response
        else:
            #校验密码的正确性
            if not user.check_password(pwd):
                return http.HttpResponseForbidden('密码错误')
            #用户 绑定
            Oauthuser.objects.create(user=user, openid=openid)

            #状态保持
            login(request, user)
            request.session.set_expiry(3600 * 24 * 2)
            # 返回响应
            # 返回到首页
            response = redirect('/')
            # 设置时间
            response.set_cookie('username', user.username, max_age=3600 * 24 * 2)
            # 返回响应
            return response